package java44th.group.bean.typehandle;

import com.fasterxml.jackson.databind.ObjectMapper;
import java44th.group.bean.common.BaseStringUtils;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @projectName: project-second
 * @package: java44th.group.bean.common
 * @className: StringArrayTypeHandle
 * @author: 杨浩祥
 * @description: TODO
 * @date: 2022/10/12 19:05
 * @version: 1.0
 */
@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringArrayTypeHandle implements TypeHandler<String[]> {
    ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, String[] strings, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(strings);
        preparedStatement.setString(index,value);
    }

    @Override
    public String[] getResult(ResultSet resultSet, String columName) throws SQLException {
        String result = resultSet.getString(columName);
        return transferStringToStringArray(result);
    }

    @Override
    public String[] getResult(ResultSet resultSet, int index) throws SQLException {
        String result = resultSet.getString(index);
        return transferStringToStringArray(result);
    }

    @Override
    public String[] getResult(CallableStatement callableStatement, int index) throws SQLException {
        String result = callableStatement.getString(index);
        return transferStringToStringArray(result);
    }

    @SneakyThrows
    private String[] transferStringToStringArray(String result) {
        if (!BaseStringUtils.isEmpty(result)){
            String[] strings = objectMapper.readValue(result, String[].class);
            return strings;
        }
        return new String[0];
    }
}
